<?php
/***
 * 赠品后台Service
 *
 *
 * @author    lanhongjie <lanhj@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */


namespace App\Services\GiftService;

use App\Services\BrandService\BrandToolService;
use App\Services\ImgServices\ImgTool;
use App\Services\Tool\ImageProcessor\ImagickTool;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
class GiftBackService
{
    protected $imagickTool;
    protected $imgTool;

    /**
     * GiftBackService constructor.
     */
    public function __construct(ImagickTool $imagickTool,ImgTool $imgTool)
    {
        $this->imagickTool=$imagickTool;
        $this->imgTool=$imgTool;
    }

    /***
     * 添加赠品
     * @param $gift
     * @return bool
     */
    public function addGift($gift){
        $insert_data=array();
        if(!empty($gift['image'])){
            $save_path=$this->imgTool->imgSave($gift['image']);
            if(!empty($save_path)){
                @$image_thumb=$this->imgTool->getImgThumbByImgPath($save_path,300,300);
                $insert_data['original_image']= $save_path;
                $insert_data['thumbnail']= $image_thumb;
            }
        }
        $insert_data['begin_time']= $gift['begin_time'];
        $insert_data['end_time']= $gift['end_time'];
        $insert_data['name']= $gift['name'];
        $insert_data['gift_desc']= $gift['gift_desc'];
        $insert_data['param_desc']= $gift['param_desc'];
        $insert_data['state']= 1;
        $insert_data['created_at']= time();
        $insert_data['updated_at']= time();
        $res=DB::table('gifts')->insert($insert_data);
        return ($res==1)?true:false;
    }
    /***
     * 赠品搜索
     * @param $search
     * @return mixed
     */
    public function SearchGifts($search)
    {
        $gifts= DB::table('gifts')->where('name','like','%'.$search.'%')
            ->where('state',1)
            ->select('id','name')
            ->get();
        return $gifts;
    }
    /***
     * 根据赠品id获取赠品
     * @param $id
     * @return object
     */
    public function getGiftDetailById($id,$state=1)
    {
        if(empty($id)){
            return null;
        }
        $query=DB::table('gifts')->where(array('id'=>$id));
        if($state===1){
            $query->where('state',1);
        }
        $gift=$query->first();
        return $gift;
    }

    /***
     * 更新赠品
     * @param array $gift
     * @return mixed
     */
    public function giftUpdate(array $gift)
    {
        try{
        DB::beginTransaction();
//            赠品使用范围，使用时间更新
        $favorable_gift=array();
         if(isset($gift['activity_id'])){
             $favorable_gift['activity_id']=$gift['activity_id'];
         }
        if(isset($gift['start_time'])&&isset($gift['end_time'])){
            $favorable_gift['updated_at']=time();
            DB::table('favorable_gifts')->where(array('gift_id'=>$gift['id']))
                                          ->update($favorable_gift);
        }
        $gift['state']=1;
        $gift['updated_at']=time();
        $res=DB::table('gifts')->where(array('id'=>$gift['id']))->update($gift);
        return $res;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e);
            return 0;
        }finally{
            DB::commit();
        }
    }

    /***
     * 删除赠品
     * @param $id
     * @return mixed
     */
    public function giftDelete($id)
    {
        $res=DB::table('gifts')->where(array('id'=>$id))
            ->update(array(
                'state'=>0,
                'updated_at'=>time(),
            ));
        DB::table('favorable_gifts')->where(array(
            'gift_id'=>$id,
            'state'=>1
        ))->update(array(
            'updated_at'=>time(),
            'state'=>0
        ));
        return $res;
    }
    /**
     * 获取赠品列表
     * @return mixed
     */
    public function getGiftList()
    {
        $gifts=DB::table('gifts')->where(array('state'=>1))
                                 ->orderBy('created_at', 'DESC')
                                 ->paginate(10);
        foreach ($gifts as $gift){
            $gift->thumbnail=ImgTool::getImgUrlByImgPath($gift->thumbnail);
            $gift->original_image=ImgTool::getImgUrlByImgPath($gift->original_image);
        }
        return $gifts;
    }
    /**
     * 数据验证
     * @param Request $request
     * @param $check_data
     * @return mixed
     */
    public function store(Request $request,$check_data)
    {
        $v = Validator::make($request->all(), $check_data);
        return $v;
    }

    /***
     * 获取赠品
     * @param $id
     * @return mixed
     */
    public function getGiftById($id){
        if(empty($id)){
            $id=0;
        }
        return DB::table('gifts')->where(array('id'=>$id))->first();
    }

    /***
     * 分页赠品映射
     * @param $gift_id
     * @return mixed
     */
    public function getFavorableGiftsByGiftId($gift_id)
    {

        if(empty($gift_id)){
            $gift_id=0;
        }
        $favorable_gifts=DB::table('favorable_gifts')->where(array(
                                   'gift_id'=>$gift_id,
                                   'state'=>1
                                  ))
                                  ->orderBy('updated_at', 'DESC')
                                  ->paginate(10);
        foreach ($favorable_gifts as $favorable_gift){
            $res_name='';
            if($favorable_gift->type==1){
                //获取产品名
                $res_name=$this->getProductTempNameById($favorable_gift->reg_id);
            }elseif($favorable_gift->type==3){
                //获取品牌名
                $res_name=$this->getBrandNameById($favorable_gift->reg_id);
            }
            $res_name=(!isset($res_name)||empty($res_name))?'':$res_name;
            $favorable_gift->res_name=$res_name;
        }
        return $favorable_gifts;
    }

    /***
     * 获取全部赠品映射
     * @param $gift_id
     * @return mixed
     */
    public function getFavorableAllGiftsByGiftId($gift_id)
    {

        if(empty($gift_id)){
            $gift_id=0;
        }
        $favorable_gifts=DB::table('favorable_gifts')->where(array(
                                   'gift_id'=>$gift_id,
                                   'state'=>1
                                    ))
                                    ->orderBy('type', 'DESC')
                                    ->get();
        foreach ($favorable_gifts as $favorable_gift){
            if($favorable_gift->type==1){
                $res_name=$this->getProductTempNameById($favorable_gift->reg_id);
            }elseif ($favorable_gift->type==2){
                $res_name=$this->getProductNameById($favorable_gift->reg_id);
            }elseif($favorable_gift->type==3){
                $res_name=BrandToolService::getBrandNameByBrandId($favorable_gift->reg_id);
            }
            $res_name=(!isset($res_name)||empty($res_name))?'':$res_name;
            $favorable_gift->res_name=$res_name;
        }
        return $favorable_gifts;
    }
    /***
     * 删除赠品下的资源绑定
     * @param $gift_id
     * @return bool
     */
    public function deleteFavorableGiftByGiftId($gift_id){
        if(empty($gift_id)||is_int($gift_id)){
            return false;
        }
        $del_res= DB::table('favorable_gifts')->wherr(array(
            'gift_id'=>$gift_id,
            'state'=>1,
        ))->update(array(
            'updated_at'=>time(),
            'state'=>0
        ));
        return ($del_res==0)?false:true;
    }
    /***
     * 查看资源是不是已经绑定过赠品
     * @param $gift_id
     * @param $reg_id
     * @param $type
     * @param int $state
     * @return bool
     */
    public function favorableGiftIsBind($gift_id,$reg_id,$type,$state=1){
        $query= DB::table('favorable_gifts')->wherr(array(
            'type'=>$type,
        ));
        if($type!==0){
            $query->where(array('gift_id'=>$gift_id,'reg_id'=>$reg_id));
        }
        if($state===1){
            $query->where('state',1);
        }
        $num=$query->count();
        return empty($num)?false:true;
    }
    /**
     * 产品id获取产品名
     * @param $product_id
     * @return string
     */
    public function getProductNameById($product_id){
        if(empty($product_id)){
            return '';
        }
        $product_title=DB::table('products')->where(array('product_id'=>$product_id))
            ->value('title');
        return empty($product_title)?'':$product_title;
    }
    /***
     * 获取产品模板名
     * @param $product_temp_id
     * @return string
     */
    public function getProductTempNameById($product_temp_id){
        if(empty($product_temp_id)){
            return '';
        }
        $name=DB::table('product_temps')->where(array('product_temp_id'=>$product_temp_id))
            ->orderBy('updated_at','DESC')
            ->value('name');
        return empty($name)?'':$name;
    }

    /**
     * 品牌id获取品牌名
     * @param $brand_id
     * @return string
     */
    public function getBrandNameById($brand_id){
        if(empty($brand_id)){
            return '';
        }
        $brand_name=DB::table('brands')->where(array('brand_id'=>$brand_id))->value('brand_name');
        return empty($brand_name)?'':$brand_name;
    }

    /***
     * 赠品和优惠资源绑定删除
     * @param $id
     * @return bool
     */
    public function favorableGiftDelete($id)
    {
        if(empty($id)){
            return false;
        }
        $res=DB::table('favorable_gifts')->where(array(
            'id'=>$id
        ))->update(array(
            'updated_at'=>time(),
            'state'=>0
        ));
        return ($res==1)?true:false;
    }

    /***
     * 更新赠品库存
     * @param $id
     * @param $num
     * @return bool
     */
    public function updateStock($id,$num)
    {
        if(empty($id)){
            return false;
        }
        $res= DB::table('favorable_gifts')->where(array('id' => $id, 'state' => 1))
                                          ->update(array(
                                                    'stock'=>$num,
                                                    'updated_at'=>time()
                                          ));
        return ($res==1)?true:false;
    }

    /***
     *  更新优惠资源，对应满订单额度时，赠送对应赠品
     * @param $id
     * @param $quota 订单额度
     * @return bool
     */
    public function updateQuota($id,$quota)
    {
        if(empty($id)){
            return false;
        }
        $res= DB::table('favorable_gifts')->where(array('id' => $id, 'state' => 1))
                                           ->update(array(
                                           'quota'=>$quota,
                                           'updated_at'=>time()
                                            ));
        return ($res==1)?true:false;
    }
    /***
     * 更新赠品对应优惠资源使用时间
     * @param array $gift
     * @return bool
     */
    public function updateGiftUseTime(array  $gift)
    {
        if(empty($gift)){
            return false;
        }
        $res= DB::table('favorable_gifts')->where(array('id' => $gift['id'], 'state' => 1))
                                           ->update(array(
                                                'begin_time'=>$gift['begin_time'],
                                                'end_time'=>$gift['end_time'],
                                                'updated_at'=>time()
                                            ));
        return ($res==1)?true:false;
    }

    /***
     * 搜索产品
     * @param $search
     * @return mixed
     */
    public function SearchProducts($search)
    {
        $products = DB::table('products')->where('title','like','%'.$search.'%')
            ->where('state',1)
            ->select('product_id as res_id','title as name')
            ->get();
        foreach ($products as $product){
            $product->name=$product->name.'(产品Id:'.$product->res_id.')';
        }
        return $products;
    }

    /***
     * 搜索产品模板
     * @param $search
     * @return mixed
     */
    public function SearchProductTemps($search)
    {
        $product_temps = DB::table('product_temps')->where('name','like','%'.$search.'%')
            ->where('state',1)
            ->select('product_temp_id as res_id','name')
            ->get();
        foreach ($product_temps as $product_temp){
            $product_temp->name=$product_temp->name.'(产品模板Id:'.$product_temp->res_id.')';
        }
        return $product_temps;
    }

    /***
     * 品牌搜索
     * @param $search
     * @return mixed
     */
    public function SearchBrands($search)
    {
        $brands = DB::table('brands')->where('brand_name','like','%'.$search.'%')
            ->where('state',1)
            ->select('brand_id as res_id','brand_name as name')
            ->get();
        foreach ($brands as $brand){
            $brand->name=$brand->name.'(品牌Id:'.$brand->res_id.')';
        }
        return $brands;
    }

    /***
     * 判断优惠资源是不是已经绑定过
     * @param $gift_id
     * @param $reg_id
     * @param $type
     * @param int $state
     * @return bool
     */
    public function regIdHasBindingGiftId($gift_id,$reg_id,$type,$state=1)
    {
        $query=DB::table('favorable_gifts')
            ->where(array('type'=>$type));
        if ($type!==0){
            $query->where(array('gift_id'=>$gift_id,'reg_id'=>$reg_id,));
        }
        if($state===1){
            $query->where('state',1);
        }
        $num=$query->count();
        return ($num==0)?false:true;
    }

    /***
     * 添加赠品绑定优惠资源
     * @param array $data
     * @return bool
     */
    public function addGiftMap(array $data){
        try{
            $gift_id=intval($data['gift_id']);
            $type=$data['type'];
            $reg_id=$data['reg_id'];
            $data['updated_at']=time();
            $data['state']=1;
            $gift=$this->getGiftById($gift_id);
            if(empty($gift)){
                return false;
            }
            $data['begin_time']=$gift->begin_time;
            $data['end_time']=$gift->end_time;
            if($type===0){
                DB::table('favorable_gifts')->where(array('gift_id'=>$gift_id,'state'=>1))
                    ->update(array('state'=>0,'updated_at'=>time()));
            }
            $exist=$this->regIdHasBindingGiftId($gift_id,$reg_id,$type,0);
            if($exist){
                $query=DB::table('favorable_gifts')
                    ->where(array('type'=>$type));
                if($type!==0){
                    $query->where(array('gift_id'=>$gift_id,'reg_id'=>$reg_id));
                }
                $num=$query->update($data);
            }else{
                $data['created_at']=time();
                $num=DB::table('favorable_gifts')->insert($data);
            }
            return empty($num)?false:true;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 判断产品是不是存在
     * @param $product_id
     * @return bool
     */
    public function productExistByProductId($product_id){
        if(empty($product_id)){
            return false;
        }
        $num=DB::table('products')
            ->where(array('product_id'=>$product_id,'state'=>1))
            ->count();
        return ($num===0)?false:true;
    }
}